#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2016/10/26 10:47
# @Author  : xycfree
# @Link    : http://example.org
# @Version : $
import os

import paramiko
# from paramiko.sftp_client import SFTP, SFTPClient
import db, conf


class Upload(object):
	def __init__(self):
		pass

	#创建文件上传目录
	def load_path(self, ip):
		self.query = 'SELECT username, password, port FROM cmdb WHERE ip="{ip}"'.format(ip=ip)
		try:
			data = db.db_select_on(self.query)
			username, password, port = data
			path = conf._REMOTE_FOLDER
			command = 'mkdir '+ path
			# u = Upload()
			result = Upload().run(ip, username, password, int(port), command)
			if not result:
				result = {
					'code': 0000,
					'message': conf._code.get(0000, '执行成功')
				}
			else:
				result = {
					'code': 2016,
					'message': conf._code.get(2016, '远程文件已存在')
				}
			result['ip'] = ip
			return result
		except Exception, e:
			result = {
				'code': 2009,
				'message': conf._code.get(2009,'数据库异常 ')+ str(e)}
			result['ip'] = ip
			return result

	# paramiko命令执行
	def run(self, ip, username, password, port, command):
		ssh = paramiko.SSHClient()  # paramiko 建立连接
		ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
		try:
			ssh.connect(hostname=ip, username=username, password=password, port=int(port))
			stdin, stdout, stderr = ssh.exec_command(command)
			err = stderr.read()  # 只能读取一次
			if err:
				return err
			else:
				return stdout.read()

		except Exception, e:
			return 'Error: ' + str(e)

	#文件上传
	def upload_file(self, ip, localpath, remotepath,filename):
		self.query = 'SELECT username, password, port FROM cmdb WHERE ip="{ip}"'.format(ip=ip)
		try:
			data = db.db_select_on(self.query)
			username, password, port = data

			t = paramiko.Transport((ip,int(port)))
			t.connect(username = username, password = password)
			sftp = paramiko.SFTPClient.from_transport(t)
			sftp.put(os.path.join(localpath,filename), remotepath+'/'+filename) #本地文件上传到服务器
			t.close()
			result = {
				'code': 0000,
				'message': '上传成功'
			}
			result['ip'] = ip
			return result
		except Exception, e:
			result = {
				'code': 2017,
				'message': conf._code.get(2017,'上传失败 ') + str(e)
			}
			result['ip'] = ip
			return result

	#上传文件信息写入数据库
	def insert_file(self,filename,uuid_name,remotepath):
		self.query = '''INSERT INTO upload(upname,uuid,folder)
			VALUES( '{upname}', '{uuid}', '{folder}' )'''.format(upname=filename, uuid=uuid_name, folder=remotepath)
		try:
			result = db.db_insert_on(self.query)
			return result
		except Exception, e:
			return str(e)

if __name__ == '__main__':
	u = Upload()
	# print u.run('123.56.189.127','root','LOcE1-aWbfk2FNU=',22,'uptime')
	res = u.load_path('192.168.40.128')
	print res['code'],res['message']
	print u.upload_file('192.168.40.128',r'D:\Testing\A_Byte_of_Python.pdf', '/home/wang/uploads/A_Byte_of_Python.pdf')
